package com.abso.mp3tunes.locker.ui.actions;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;

import com.abso.mp3tunes.locker.core.LockerServiceException;
import com.abso.mp3tunes.locker.core.data.Playlist;
import com.abso.mp3tunes.locker.core.data.PlaylistData;
import com.abso.mp3tunes.locker.ui.LockerPlugin;
import com.abso.mp3tunes.locker.ui.viewers.LockerViewer;

/**
 * Action able to delete a set of existing playlists.
 */
public class DeletePlaylistsAction extends AbstractLockerViewerAction {

	/** The selected playlists. */
	private List playlists;

	/**
	 * Constructs a new action.
	 * 
	 * @param lockerViewer
	 *            the Locker tree viewer.
	 */
	public DeletePlaylistsAction(LockerViewer lockerViewer) {
		super("Delete", PlatformUI.getWorkbench().getSharedImages()
				.getImageDescriptor(ISharedImages.IMG_TOOL_DELETE),
				lockerViewer);
	}

	/**
	 * Sets the current selection.
	 * 
	 * @param playlists
	 *            the selected playlists.
	 */
	public void setPlaylists(List playlists) {
		this.playlists = playlists;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.jface.action.Action#run()
	 */
	public void run() {
		Shell shell = LockerPlugin.getActiveWorkbenchShell();
		Display display = shell.getDisplay();
		if (!MessageDialog
				.openQuestion(shell, "Confirm Delete",
						"Are you sure you want to delete the selected "
								+ ((playlists.size() == 1) ? "playlist?"
										: "playlists?"))) {
			return;
		}
		BusyIndicator.showWhile(display, new Runnable() {
			public void run() {
				List deletedPlaylists = new ArrayList(playlists.size());
				for (Iterator i = playlists.iterator(); i.hasNext();) {
					Playlist playlist = (Playlist) i.next();
					try {
						PlaylistData result = LockerPlugin.getDefault()
								.getLockerService().deletePlaylist(
										playlist.getId());
						if (result.getPlaylistsDeleted() > 0) {
							deletedPlaylists.add(playlist);
						}
					} catch (LockerServiceException e) {
						showErrorDialog("Error",
								"Unable to delete the playlist '"
										+ playlist.getTitle() + "'",
								"Error deleting the playlist", e);
					}
				}
				getLockerViewer().remove(deletedPlaylists.toArray());
			}
		});
	}

}
